<template>
	<view class="detail-container">
		<!-- 顶栏 -->
		<view class="top-bar fixed">
			<view class="top-bar-content">
				<i class="ri-arrow-left-line back-icon" @click="onBack"></i>
				<text class="detail-title">动态详情</text>
				<view class="right-icons">
					<i class="ri-more-2-line back-icon"></i>
				</view>
			</view>
		</view>

		<!-- 动态内容 -->
		<view class="community-card">
			<view class="card-header">
				<up-avatar :src="community.candidate.candidateImg" shape="circle" class="avatar"></up-avatar>
				<view class="header-info">
					<text class="candidate-name">{{ community.candidate.name }}</text>
					<text class="time">{{ formatTime(community.time) }}</text>
				</view>
			</view>
			<view class="card-content">
				<text class="community-title">{{ community.communityTitle }}</text>
				<view v-if="community.communityType === 'video'">
					<text>{{ community.communityContent }}</text>
					<video :src="community.videoPath" controls />
				</view>
				<view v-if="community.communityType === 'image'">
					<text>{{ community.communityContent }}</text>
					<view class="image-grid">
						<image v-for="(img, imgIndex) in community.imageList" :key="imgIndex" :src="img" mode="widthFix" @click="onImageClick(community.imageList, imgIndex)" />
					</view>
				</view>
				<view v-if="community.communityType === 'article'">
					<text>{{ community.communityContent }}</text>
				</view>
			</view>
			<view class="card-footer">
				<text v-if="community.reportStatus > 20" class="report-warning">该动态被多人举报，请注意真实性</text>
			</view>
		</view>

		<up-divider text="评论区" textSize="18"></up-divider>

		<!-- 评论区域 -->
		<view class="comments-section">
			<up-empty v-if="comments.length === 0" mode="data" text="暂无评论"></up-empty>
			<view v-for="(comment, index) in comments" :key="comment.commentId">
				<!-- 根评论展示 -->
				<view v-if="!comment.commentIndex">
					<view class="comment-item">
						<up-avatar :src="comment.candidate.candidateImg" shape="circle" class="avatar"></up-avatar>
						<view class="comment-content">
							<text class="commenter-name">{{ comment.candidate.name }}</text>
							<text class="comment-text">{{ comment.commentContent }}</text>
							<text class="comment-time">{{ formatTime(comment.time) }}</text>
							<view class="comment-actions">
								<view @click="onLikeClick(comment)" class="like-btn">
									<i :class="comment.isLiked ? 'ri-thumb-up-fill' : 'ri-thumb-up-line'"></i>
									<text>{{ comment.commentLikeCount }}</text>
								</view>
								<view @click="onReplyClick(comment)" class="reply-btn">
									<text>回复</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 回复评论展示 -->
					<view v-for="reply in comments.filter((c) => c.commentIndex === comment.commentId)" :key="reply.commentId" class="reply-comment-item">
						<view class="reply-header">
							<image :src="reply.candidate.candidateImg" class="avatar" />
							<view class="reply-content">
								<text class="reply-name">{{ reply.candidate.name }} 回复</text>
								<text class="reply-text">{{ reply.commentContent }}</text>
								<text class="reply-time">{{ formatTime(reply.time) }}</text>
								<view class="reply-actions">
									<view @click="onLikeClick(reply)" class="like-btn">
										<i :class="reply.isLiked ? 'ri-thumb-up-fill' : 'ri-thumb-up-line'"></i>
										<text>{{ reply.commentLikeCount }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底栏：评论输入框 -->
		<view class="footer-bar fixed">
			<view class="comment-section">
				<input v-model="replyContent" class="comment-input" placeholder="写下你的看法..." @click="onReplyClick(this.community)" @input="inputSelect" />
				<i class="ri-send-plane-2-line send-icon1" @click="sendReply"></i>
			</view>
			<view @click="onLikeClick(this.community)" class="icon-item">
				<i :class="community.isLiked ? 'ri-thumb-up-fill highlight' : 'ri-thumb-up-line'" class="icon"></i>
				<text>{{ community.likeCount }}</text>
			</view>
			<view @click="onStarClick(this.community)" class="icon-item">
				<i :class="community.isStarred ? 'ri-star-fill highlight' : 'ri-star-line'" class="icon"></i>
				<text>{{ community.starCount }}</text>
			</view>
		</view>
	</view>

	<!-- 评论回复输入框弹窗 -->
	<view v-if="showReplyBox" :class="['overlay', modalClosing ? 'modal-closing' : '']" @click="closeReplyBox">
		<view ref="replyBox" :class="['reply-box', modalClosing ? 'modal-content-closing' : '']" @click.stop>
			<textarea auto-focus v-model="replyContent" class="reply-input" placeholder="写下你的看法..."></textarea>
			<i class="ri-send-plane-2-line send-icon" @click="sendReply"></i>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			community: {}, // 动态详情
			comments: [], // 评论列表
			showReplyBox: false, // 控制回复框的显示
			modalClosing: false, // 控制回复框关闭动画
			replyContent: '', // 评论框的内容（与评论合并）
			currentComment: null // 当前点击的评论
		};
	},
	methods: {
		onBack() {
			// 返回上一个页面
			uni.navigateBack();
		},
		// 动态点赞逻辑
		onLikeClick(community) {
			// 如果是用户第一次点击，记录原始点赞状态
			if (community.originalLiked === undefined) {
				community.originalLiked = community.isLiked;
			}
			// 更新点赞状态
			community.isLiked = !community.isLiked;
			community.isLiked ? community.likeCount++ : community.likeCount--;
			// 防抖逻辑：2秒后发送请求
			clearTimeout(this.debounceTimer);
			this.debounceTimer = setTimeout(() => {
				// 如果状态和首次状态不一致，发送请求
				if (community.isLiked !== community.originalLiked) {
					if (community.isLiked) {
						this.$api
							.likeCommunity({
								communityId: community.communityId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '点赞成功',
									icon: 'none'
								});
								community.originalLiked = undefined;
							});
					} else {
						this.$api
							.unlikeCommunity({
								communityId: community.communityId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '取消点赞成功',
									icon: 'none'
								});
								community.originalLiked = undefined;
							});
					}
				} else {
					console.log('点赞状态未改变');
				}
			}, 2000);
		},
		// 评论点赞逻辑
		onLikeLikeClick(comment) {
			if (comment.originalLiked === undefined) {
				comment.originalLiked = comment.isLiked;
			}
			comment.isLiked = !comment.isLiked;
			comment.isLiked ? comment.commentLikeCount++ : comment.commentLikeCount--;
			clearTimeout(this.debounceTimer);
			this.debounceTimer = setTimeout(() => {
				if (comment.isLiked !== comment.originalLiked) {
					if (comment.isLiked) {
						this.$api
							.likeComment({
								communityId: this.community.communityId,
								commentId: comment.commentId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '点赞成功',
									icon: 'none'
								});
								comment.originalLiked = undefined;
							});
					} else {
						this.$api
							.unlikeComment({
								communityId: this.community.communityId,
								commentId: comment.commentId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '取消点赞成功',
									icon: 'none'
								});
								comment.originalLiked = undefined;
							});
					}
				} else {
					console.log('点赞状态未改变');
				}
			}, 2000);
		},
		// 动态收藏逻辑
		onStarClick(community) {
			if (community.originalStared === undefined) {
				community.originalStared = community.isStarred;
			}
			community.isStarred = !community.isStarred;
			community.isStarred ? community.starCount++ : community.starCount--;
			clearTimeout(this.debounceTimer2);
			this.debounceTimer2 = setTimeout(() => {
				if (community.isStarred !== community.originalStared) {
					if (community.isStarred) {
						this.$api
							.addCollection({
								communityId: community.communityId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '收藏成功',
									icon: 'none'
								});
							});
						community.originalStared = undefined;
					} else {
						this.$api
							.deleteCollection({
								communityId: community.communityId,
								candidateId: uni.getStorageSync('user').candidateId
							})
							.then(() => {
								uni.showToast({
									title: '取消收藏成功',
									icon: 'none'
								});
							});
						community.originalStared = undefined;
					}
				} else {
					console.log('收藏状态未改变');
				}
			}, 2000);
		},
		// 格式化时间
		formatTime(time) {
			const diff = Date.now() - new Date(time);
			if (diff < 60 * 1000) {
				return `${Math.floor(diff / 1000)}秒前`;
			} else if (diff < 60 * 60 * 1000) {
				return `${Math.floor(diff / (60 * 1000))}分钟前`;
			} else if (diff < 24 * 60 * 60 * 1000) {
				return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
			} else {
				return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
			}
		},
		// 预览图片
		onImageClick(imgPath, index) {
			uni.previewImage({
				urls: imgPath,
				current: index
			});
		},
		onReplyClick(comment) {
			if (this.community.isCommented === true) {
				uni.showToast({
					title: '不能重复评论',
					icon: 'none'
				});
				return;
			}
			// 点击回复按钮时，打开回复框
			this.showReplyBox = true;
			this.currentComment = comment; // 记录当前评论
		},
		closeReplyBox() {
			this.modalClosing = true; // 添加遮罩淡出动画
			setTimeout(() => {
				this.modalClosing = false; // 重置遮罩动画状态
				this.showReplyBox = false;
			}, 300); // 动画时间为 0.3 秒
		},
		sendReply() {
			if (this.community.isCommented === true) {
				uni.showToast({
					title: '不能重复评论',
					icon: 'none'
				});
				return;
			}
			// 发送回复
			if (this.replyContent.trim()) {
				// 创建新的回复评论
				const newReply = {
					communityId: this.currentComment.communityId,
					commentIndex: this.currentComment.commentId === 0 ? null : this.currentComment.commentId, // 关联回复的评论 ID
					commentContent: this.replyContent,
					candidateId: uni.getStorageSync('user').candidateId,
					commentLikeCount: 0,
					isLiked: false
				};
				this.$api.publishComment(newReply).then(() => {
					uni.showToast({
						title: '回复成功',
						icon: 'success'
					});
				});
				this.$api
					.getCommunityComment({
						communityId: this.currentComment.communityId,
						candidateId: uni.getStorageSync('user').candidateId
					})
					.then((res) => {
						this.comments = res.data;
					});
				// 关闭回复框
				this.closeReplyBox();
				this.replyContent = ''; // 清空回复内容
			} else {
				// 可以在这里添加提示：回复内容不能为空
				console.log('回复内容不能为空');
			}
		},
		inputSelect() {
			if (this.community.isCommented === true) {
				this.replyContent = this.replyContent.slice(0, 0);
			}
		}
	},
	onLoad(options) {
		// 从后端获取数据
		const communityId = options.id;
		this.$api
			.getCommunityDetail({
				communityId,
				candidateId: uni.getStorageSync('user').candidateId
			})
			.then((res) => {
				this.community = res;
			});
		this.$api
			.getCommunityComment({
				communityId,
				candidateId: uni.getStorageSync('user').candidateId
			})
			.then((res) => {
				this.comments = res.data;
			});
		if (options.isComment) {
			this.showReplyBox = true;
		}
	}
};
</script>

<style scoped>
@import '@/static/remixicon.css';

.detail-container {
	padding-top: 60px;
	padding-bottom: 60px;
}
.top-bar {
	background-color: #59a0ff;
	padding: 10px;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
}
.top-bar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.back-icon {
	font-size: 24px;
	color: white;
	cursor: pointer;
}
.detail-title {
	color: white;
	font-size: 18px;
	font-weight: bold;
}

.footer-bar {
	background-color: #ffffff;
	padding: 10px;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
	z-index: 20;
}
.comment-section {
	display: flex;
	align-items: center;
}
.comment-input {
	border: 1px solid #e0e0e0;
	width: 400rpx;
	border-radius: 20px;
	padding: 8px 15px;
	font-size: 14px;
}
.send-icon1 {
	font-size: 24px;
	color: #59a0ff;
	margin-left: 10px;
	cursor: pointer;
}
.action-icons {
	display: flex;
	align-items: center;
	margin-left: 15px;
}
.action-icon {
	font-size: 24px;
	color: #666;
	margin-left: 15px;
	cursor: pointer;
}
.community-card {
	margin-bottom: 20px;
	padding: 15px;
	background-color: #ffffff;
}
.card-header {
	display: flex;
	align-items: center;
}
.header-info {
	margin-left: 10px;
}
.avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
}
.candidate-name {
	font-weight: bold;
	font-size: 16px;
}
.time {
	font-size: 12px;
	color: #999;
	margin-left: 10px;
}
.card-content {
	margin-top: 10px;
}
.image-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 5px;
	margin-top: 10px;
}
.image-grid image {
	width: 32%;
	border-radius: 5px;
}
.community-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 10px;
}
.card-footer {
	display: flex;
	justify-content: space-between;
	margin-top: 15px;
	align-items: center;
}
.icon-group {
	display: flex;
	justify-content: space-between;
	width: 100%;
}
.icon-item {
	display: flex;
	align-items: center;
	cursor: pointer;
	flex: 1;
	justify-content: center;
}
.icon {
	font-size: 24px;
	margin-right: 5px;
}
.highlight {
	color: #59a0ff;
}
.report-warning {
	color: red;
	font-size: 12px;
	text-align: right;
}

.comments-section {
	padding: 20px;
}

.comment-item {
	display: flex;
	margin-bottom: 20px;
}

.avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	margin-right: 10px;
}

.comment-content {
	flex: 1;
}

.commenter-name {
	font-weight: bold;
}

.comment-text {
	display: block;
	margin: 5px 0;
}

.comment-time {
	font-size: 12px;
	color: gray;
}

.comment-actions {
	display: flex;
	align-items: center;
}

.like-btn {
	display: flex;
	align-items: center;
	margin-right: 10px;
	cursor: pointer;
}

.like-btn i {
	font-size: 18px;
	margin-right: 5px;
}

.reply-comment-item {
	display: flex;
	margin-left: 50px; /* For indentation */
	margin-top: 10px;
}

.reply-header {
	display: flex;
}

.reply-name {
	font-weight: bold;
}

.reply-content {
	flex: 1;
}

.reply-text {
	display: block;
	margin: 5px 0;
}

.reply-time {
	font-size: 12px;
	color: gray;
}

/* 遮罩层 */
.overlay {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	z-index: 102;
	animation: fadeIn 0.3s ease forwards;
}

/* 弹窗 */
.reply-box {
	background-color: #ffffff;
	width: 100%;
	border-top-left-radius: 20px;
	border-top-right-radius: 20px;
	padding: 20px;
	animation: slideUp 0.3s ease forwards;
}

.modal-closing {
	animation: fadeOut 0.3s ease forwards;
}
.modal-content-closing {
	animation: slideDown 0.3s ease forwards;
}

/* 回复输入框 */
.reply-input {
	width: 85%;
	height: 100px;
	border: 1px solid #ddd;
	padding: 10px;
	border-radius: 5px;
	resize: none;
}

/* 发送按钮图标 */
.send-icon {
	font-size: 24px;
	color: #59a0ff;
	cursor: pointer;
	position: absolute;
	right: 20px;
	bottom: 66px;
}

/* 动画 */
@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

@keyframes fadeOut {
	from {
		opacity: 1;
	}
	to {
		opacity: 0;
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

@keyframes slideDown {
	from {
		transform: translateY(0);
	}
	to {
		transform: translateY(100%);
	}
}
</style>
